package com.fbt.transfer.app.driver.util;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import com.fbt.transfer.app.driver.MyApplication;
import java.util.StringJoiner;

/**
 * App的基础信息
 *
 * @author tuocoo
 * @date 2025-03-25
 * @since 1.0.0
 */
public class AppInfoUtils {

  public static final String APP_NAME = "driver_app";
  /**
   * 手机品牌|系统版本|appName|设备唯一标识
   *
   * @return 请求头标识
   */
  public static String getUserAgent() {
    StringJoiner joiner = new StringJoiner("|");
    joiner.add(Build.BRAND);
    joiner.add(Build.VERSION.RELEASE);
    joiner.add(APP_NAME);
    joiner.add(getAppVersion());
    joiner.add(getDeviceId());
    return joiner.toString();
  }

  private static String getAppName() {
    try {
      PackageInfo packageInfo = getPackageInfo();
      return packageInfo.applicationInfo.loadLabel(MyApplication.getApplication().getPackageManager())
          .toString();
    } catch (PackageManager.NameNotFoundException e) {
      return Constants.EMPTY_STRING;
    }
  }

  private static String getDeviceId() {
    return Settings.Secure.getString(
        MyApplication.getApplication().getContentResolver(), Settings.Secure.ANDROID_ID);
  }

  /**
   * 获取当前app版本号
   *
   * @return 版本号
   */
  public static String getAppVersion() {
    try {
      return getPackageInfo().versionName;
    } catch (Exception e) {
      return Constants.EMPTY_STRING;
    }
  }

  private static PackageInfo getPackageInfo() throws PackageManager.NameNotFoundException {
    return MyApplication.getApplication().getPackageManager().getPackageInfo(
        MyApplication.getApplication().getPackageName(), 0);
  }

  /**
   * 获取当前app版本代码
   *
   * @return 版本代码
   */
  public static long getAppCode() {
    try {
      return getPackageInfo().getLongVersionCode();
    } catch (Exception e) {
      return Integer.MAX_VALUE;
    }
  }
}